<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据抓取 - 股票财务分析报告系统</title>
    <!-- 引入Bootstrap -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.2/echarts.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .header h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 600;
        }
        .back-link {
            color: white;
            text-decoration: none;
            font-size: 1rem;
            transition: opacity 0.3s;
        }
        .back-link:hover {
            color: white;
            opacity: 0.8;
            text-decoration: none;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            margin-bottom: 1.5rem;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #667eea;
            color: white;
            border-radius: 10px 10px 0 0 !important;
            font-weight: 500;
            font-size: 1.1rem;
        }
        .card-body {
            padding: 1.5rem;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .btn-primary {
            background-color: #667eea;
            border-color: #667eea;
            padding: 0.5rem 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
            transform: translateY(-1px);
        }
        .btn-success {
            background-color: #38b2ac;
            border-color: #38b2ac;
            padding: 0.5rem 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-success:hover {
            background-color: #319795;
            border-color: #319795;
            transform: translateY(-1px);
        }
        .btn-warning {
            background-color: #ed8936;
            border-color: #ed8936;
            padding: 0.5rem 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-warning:hover {
            background-color: #dd6b20;
            border-color: #dd6b20;
            transform: translateY(-1px);
        }
        .btn-danger {
            background-color: #f56565;
            border-color: #f56565;
            padding: 0.5rem 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-danger:hover {
            background-color: #e53e3e;
            border-color: #e53e3e;
            transform: translateY(-1px);
        }
        .btn-group {
            margin-bottom: 1rem;
        }
        .btn-group .btn {
            margin-right: 0.5rem;
        }
        .badge {
            font-size: 0.8rem;
            padding: 0.4rem 0.6rem;
        }
        .badge-success {
            background-color: #38b2ac;
        }
        .badge-warning {
            background-color: #ed8936;
        }
        .badge-danger {
            background-color: #f56565;
        }
        .badge-info {
            background-color: #4299e1;
        }
        .stats-card {
            background-color: #f7fafc;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            border: 1px solid #e2e8f0;
            transition: transform 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-2px);
        }
        .stats-card .title {
            font-size: 0.9rem;
            color: #718096;
            margin-bottom: 0.5rem;
        }
        .stats-card .value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #667eea;
        }
        .highlight {
            background-color: #ebf8ff;
            border-left: 4px solid #3182ce;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0 8px 8px 0;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-content {
            text-align: center;
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 90%;
        }
        .progress {
            height: 10px;
            border-radius: 5px;
            background-color: #e2e8f0;
            overflow: hidden;
            margin: 1rem 0;
        }
        .progress-bar {
            background-color: #667eea;
            transition: width 0.3s ease;
        }
        .log-container {
            background-color: #2d3748;
            color: #e2e8f0;
            padding: 1rem;
            border-radius: 8px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            margin-top: 1rem;
        }
        .log-item {
            margin-bottom: 0.5rem;
            padding-left: 1.5rem;
            position: relative;
        }
        .log-item:before {
            content: '>';
            position: absolute;
            left: 0;
            color: #667eea;
        }
        .log-item.success {
            color: #38b2ac;
        }
        .log-item.error {
            color: #f56565;
        }
        .log-item.warning {
            color: #ed8936;
        }
        .log-item.info {
            color: #4299e1;
        }
        .stock-list-container {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            margin-top: 1rem;
        }
        .stock-item {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #e2e8f0;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        .stock-item:hover {
            background-color: #f7fafc;
        }
        .stock-item:last-child {
            border-bottom: none;
        }
        .stock-item .name {
            font-weight: 500;
            margin-right: 0.5rem;
        }
        .stock-item .code {
            color: #718096;
            font-size: 0.9rem;
        }
        .tag {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            margin: 0.25rem;
            border-radius: 4px;
            background-color: #edf2f7;
            font-size: 0.8rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .tag:hover {
            background-color: #667eea;
            color: white;
        }
        .tag.active {
            background-color: #667eea;
            color: white;
        }
        .error-message {
            color: #f56565;
            margin-top: 0.5rem;
            font-size: 0.9rem;
        }
        .form-check {
            margin-bottom: 1rem;
        }
        .form-check-label {
            font-weight: 500;
        }
    </style>
</head>
<body>
    <!-- 加载遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="loading-content">
            <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;" role="status">
                <span class="sr-only">处理中...</span>
            </div>
            <h4 class="mt-3" id="loadingTitle">数据处理中</h4>
            <p id="loadingMessage" class="mt-2 text-muted">请稍候，正在处理数据...</p>
            <div class="progress">
                <div id="loadingProgress" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
            <p class="mt-2 text-sm" id="loadingPercentage">0%</p>
        </div>
    </div>

    <!-- 头部 -->
    <header class="header">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <a href="/stockpereport/index" class="back-link">
                        <i class="fas fa-arrow-left mr-2"></i>返回列表
                    </a>
                    <h1 class="mt-1">股票财务数据抓取</h1>
                </div>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <div class="container">
        <!-- 系统状态统计 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="title">已抓取股票</div>
                    <div class="value" id="totalStockCount">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="title">最新报告数量</div>
                    <div class="value" id="latestReportCount">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="title">季度数据数量</div>
                    <div class="value" id="quarterDataCount">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="title">系统运行状态</div>
                    <div class="value" id="systemStatus"><span class="badge badge-success">正常</span></div>
                </div>
            </div>
        </div>

        <!-- 数据抓取选项卡 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-sync-alt mr-2"></i>数据抓取配置
            </div>
            <div class="card-body">
                <ul class="nav nav-tabs mb-4">
                    <li class="nav-item">
                        <a class="nav-link active" id="single-tab" data-toggle="tab" href="#single">单只股票</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="batch-tab" data-toggle="tab" href="#batch">批量抓取</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="advanced-tab" data-toggle="tab" href="#advanced">高级设置</a>
                    </li>
                </ul>
                
                <div class="tab-content">
                    <!-- 单只股票抓取 -->
                    <div class="tab-pane fade show active" id="single">
                        <div class="form-group">
                            <label for="securityCode">股票代码</label>
                            <input type="text" class="form-control" id="securityCode" placeholder="请输入股票代码，例如：600000">
                            <small class="form-text text-muted">支持A股代码（上证、深证）</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="securityName">股票名称</label>
                            <input type="text" class="form-control" id="securityName" placeholder="请输入股票名称">
                            <small class="form-text text-muted">如果不输入，系统将自动获取</small>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="process20Quarters" checked>
                            <label class="form-check-label" for="process20Quarters">
                                同时处理近20个季度数据
                            </label>
                        </div>
                        
                        <div class="btn-group mt-4">
                            <button id="fetchSingleBtn" class="btn btn-primary">
                                <i class="fas fa-download mr-2"></i>抓取单只股票数据
                            </button>
                            <button id="testConnectionBtn" class="btn btn-info">
                                <i class="fas fa-link mr-2"></i>测试连接
                            </button>
                        </div>
                    </div>
                    
                    <!-- 批量抓取 -->
                    <div class="tab-pane fade" id="batch">
                        <div class="highlight">
                            <p><i class="fas fa-info-circle mr-2"></i>批量抓取说明：</p>
                            <ul class="list-unstyled mb-0">
                                <li>• 支持批量抓取指定行业或指数成分股</li>
                                <li>• 每次批量抓取建议不超过50只股票，避免服务器负载过高</li>
                                <li>• 抓取过程中请勿关闭页面</li>
                            </ul>
                        </div>
                        
                        <div class="form-group mt-4">
                            <label>批量抓取选项</label>
                            <div class="tag-container mt-2">
                                <span class="tag" data-group="sse">上证50</span>
                                <span class="tag" data-group="csi300">沪深300</span>
                                <span class="tag" data-group="gem">创业板指</span>
                                <span class="tag" data-group="bank">银行业</span>
                                <span class="tag" data-group="tech">科技行业</span>
                                <span class="tag" data-group="medicine">医药行业</span>
                                <span class="tag" data-group="all">所有股票</span>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="customStockList">自定义股票列表（可选）</label>
                            <textarea class="form-control" id="customStockList" rows="4" placeholder="每行输入一个股票代码，例如：
600000
000001
601318"></textarea>
                            <small class="form-text text-muted">如果填写，将优先抓取自定义列表中的股票</small>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="batchProcess20Quarters" checked>
                            <label class="form-check-label" for="batchProcess20Quarters">
                                同时处理近20个季度数据
                            </label>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skipExisting">
                            <label class="form-check-label" for="skipExisting">
                                跳过已存在的最新数据
                            </label>
                        </div>
                        
                        <div class="btn-group mt-4">
                            <button id="startBatchFetchBtn" class="btn btn-success">
                                <i class="fas fa-sync-alt mr-2"></i>开始批量抓取
                            </button>
                            <button id="cancelBatchFetchBtn" class="btn btn-danger">
                                <i class="fas fa-times mr-2"></i>取消抓取
                            </button>
                        </div>
                    </div>
                    
                    <!-- 高级设置 -->
                    <div class="tab-pane fade" id="advanced">
                        <div class="form-group">
                            <label for="fetchInterval">请求间隔（毫秒）</label>
                            <input type="number" class="form-control" id="fetchInterval" value="2000" min="1000" max="10000">
                            <small class="form-text text-muted">控制抓取频率，避免被网站限制</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="timeout">超时时间（秒）</label>
                            <input type="number" class="form-control" id="timeout" value="30" min="5" max="120">
                            <small class="form-text text-muted">单次请求的最大等待时间</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="retryCount">重试次数</label>
                            <input type="number" class="form-control" id="retryCount" value="3" min="0" max="10">
                            <small class="form-text text-muted">请求失败后的重试次数</small>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="useProxy">
                            <label class="form-check-label" for="useProxy">
                                使用代理服务器
                            </label>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="enableDebug" checked>
                            <label class="form-check-label" for="enableDebug">
                                启用调试日志
                            </label>
                        </div>
                        
                        <button id="saveSettingsBtn" class="btn btn-primary mt-4">
                            <i class="fas fa-save mr-2"></i>保存设置
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据处理操作 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-tools mr-2"></i>数据处理操作
            </div>
            <div class="card-body">
                <div class="btn-group">
                    <button id="processAll20QuartersBtn" class="btn btn-warning">
                        <i class="fas fa-cogs mr-2"></i>处理所有股票近20个季度数据
                    </button>
                    <button id="deleteOldDataBtn" class="btn btn-danger">
                        <i class="fas fa-trash-alt mr-2"></i>删除旧数据
                    </button>
                    <button id="refreshStatsBtn" class="btn btn-info">
                        <i class="fas fa-chart-line mr-2"></i>刷新统计
                    </button>
                </div>
                
                <div class="form-group mt-4">
                    <label for="oldDataDays">删除多少天前的数据</label>
                    <div class="input-group">
                        <input type="number" class="form-control" id="oldDataDays" value="365" min="30" max="1095">
                        <div class="input-group-append">
                            <span class="input-group-text">天</span>
                        </div>
                    </div>
                    <small class="form-text text-muted">默认删除365天前的数据</small>
                </div>
            </div>
        </div>

        <!-- 历史记录和日志 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-history mr-2"></i>操作日志
            </div>
            <div class="card-body">
                <div class="log-container" id="logContainer">
                    <div class="log-item info">系统初始化完成</div>
                    <div class="log-item info">等待用户操作...</div>
                </div>
            </div>
        </div>

        <!-- 最近抓取的股票列表 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-list-ul mr-2"></i>最近抓取的股票
            </div>
            <div class="card-body">
                <div class="stock-list-container" id="recentStocksList">
                    <!-- 股票列表将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="mt-5 py-4 bg-light">
        <div class="container text-center text-muted">
            <p>© 2024 股票财务分析报告系统 - 数据抓取中心</p>
            <p class="small">注意：请勿频繁抓取数据，避免对目标网站造成负担</p>
        </div>
    </footer>

    <!-- 消息提示框 -->
    <div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position: fixed; top: 20px; right: 20px; min-width: 300px; z-index: 1050;">
        <div class="toast-header">
            <strong class="mr-auto" id="toastTitle">提示</strong>
            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>

    <!-- 引入jQuery和Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>

    <script>
        $(document).ready(function() {
            // 初始化页面
            initPage();
            
            // 单只股票抓取按钮点击事件
            $('#fetchSingleBtn').click(function() {
                fetchSingleStock();
            });
            
            // 测试连接按钮点击事件
            $('#testConnectionBtn').click(function() {
                testConnection();
            });
            
            // 开始批量抓取按钮点击事件
            $('#startBatchFetchBtn').click(function() {
                startBatchFetch();
            });
            
            // 取消批量抓取按钮点击事件
            $('#cancelBatchFetchBtn').click(function() {
                cancelBatchFetch();
            });
            
            // 保存设置按钮点击事件
            $('#saveSettingsBtn').click(function() {
                saveSettings();
            });
            
            // 处理所有股票近20个季度数据按钮点击事件
            $('#processAll20QuartersBtn').click(function() {
                processAll20Quarters();
            });
            
            // 删除旧数据按钮点击事件
            $('#deleteOldDataBtn').click(function() {
                deleteOldData();
            });
            
            // 刷新统计按钮点击事件
            $('#refreshStatsBtn').click(function() {
                loadSystemStats();
            });
            
            // 标签点击事件
            $('.tag').click(function() {
                $('.tag').removeClass('active');
                $(this).addClass('active');
            });
            
            // 股票代码输入框按键事件
            $('#securityCode').keypress(function(e) {
                if (e.which === 13) {
                    fetchSingleStock();
                }
            });
        });
        
        // 初始化页面
        function initPage() {
            loadSystemStats();
            loadRecentStocks();
            
            // 加载保存的设置
            loadSettings();
        }
        
        // 加载系统统计
        function loadSystemStats() {
            addLog('正在加载系统统计信息...', 'info');
            
            $.ajax({
                url: '/stockpereport/api/stats',
                type: 'GET',
                success: function(data) {
                    if (data.code === 200 && data.data) {
                        $('#totalStockCount').text(data.data.totalStockCount || 0);
                        $('#latestReportCount').text(data.data.latestReportCount || 0);
                        $('#quarterDataCount').text(data.data.quarterDataCount || 0);
                        $('#systemStatus').html('<span class="badge badge-success">正常</span>');
                        addLog('系统统计信息加载完成', 'success');
                    }
                },
                error: function() {
                    addLog('系统统计信息加载失败', 'error');
                }
            });
        }
        
        // 加载最近抓取的股票
        function loadRecentStocks() {
            $.ajax({
                url: '/stockpereport/api/recent-stocks',
                type: 'GET',
                success: function(data) {
                    if (data.code === 200 && data.data) {
                        renderRecentStocks(data.data);
                    }
                },
                error: function() {
                    addLog('最近抓取股票列表加载失败', 'error');
                }
            });
        }
        
        // 渲染最近抓取的股票列表
        function renderRecentStocks(stocks) {
            let container = $('#recentStocksList');
            container.empty();
            
            if (stocks.length === 0) {
                container.append('<div class="stock-item text-muted text-center py-3">暂无抓取记录</div>');
                return;
            }
            
            stocks.forEach(function(stock) {
                let item = $('<div class="stock-item"></div>');
                item.append(`<span class="name">${stock.securityName}</span>`);
                item.append(`<span class="code">${stock.securityCode}</span>`);
                item.append(`<div class="text-xs text-muted mt-1">更新时间: ${formatDateTime(stock.updateTime)}</div>`);
                
                // 添加点击事件
                item.click(function() {
                    window.location.href = `/stockpereport/detail?securityCode=${stock.securityCode}`;
                });
                
                container.append(item);
            });
        }
        
        // 抓取单只股票数据
        function fetchSingleStock() {
            let securityCode = $('#securityCode').val().trim();
            let securityName = $('#securityName').val().trim();
            let process20Quarters = $('#process20Quarters').prop('checked');
            
            if (!securityCode) {
                showToast('错误', '请输入股票代码', 'danger');
                return;
            }
            
            showLoading('数据抓取中', '正在抓取股票数据，请稍候...');
            addLog(`开始抓取股票: ${securityCode} (${securityName || '自动获取'})`, 'info');
            
            let url = `/stockpereport/fetch?securityCode=${securityCode}`;
            if (securityName) url += `&securityName=${encodeURIComponent(securityName)}`;
            if (process20Quarters) url += '&process20Quarters=true';
            
            $.ajax({
                url: url,
                type: 'GET',
                success: function(data) {
                    hideLoading();
                    if (data.success) {
                        showToast('成功', data.message, 'success');
                        addLog(`股票数据抓取成功: ${securityCode}`, 'success');
                        
                        // 刷新统计和列表
                        loadSystemStats();
                        loadRecentStocks();
                    } else {
                        showToast('失败', data.message, 'danger');
                        addLog(`股票数据抓取失败: ${data.message}`, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('错误', '网络请求失败，请稍后重试', 'danger');
                    addLog('网络请求失败，可能是服务器错误或网络问题', 'error');
                }
            });
        }
        
        // 测试连接
        function testConnection() {
            showLoading('测试连接中', '正在测试与数据源的连接...');
            addLog('开始测试数据源连接...', 'info');
            
            $.ajax({
                url: '/stockpereport/test-connection',
                type: 'GET',
                timeout: 5000,
                success: function(data) {
                    hideLoading();
                    if (data.success) {
                        showToast('成功', '连接成功，数据源可访问', 'success');
                        addLog('数据源连接测试成功', 'success');
                    } else {
                        showToast('失败', '连接失败: ' + data.message, 'danger');
                        addLog('数据源连接测试失败: ' + data.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('错误', '连接超时或服务器错误', 'danger');
                    addLog('数据源连接测试超时或服务器错误', 'error');
                }
            });
        }
        
        // 开始批量抓取
        function startBatchFetch() {
            let selectedGroup = $('.tag.active').data('group');
            let customStockList = $('#customStockList').val().trim();
            let batchProcess20Quarters = $('#batchProcess20Quarters').prop('checked');
            let skipExisting = $('#skipExisting').prop('checked');
            
            // 如果有自定义列表，优先使用
            let fetchType = customStockList ? 'custom' : selectedGroup;
            
            if (!fetchType) {
                showToast('错误', '请选择要抓取的股票组或输入自定义列表', 'danger');
                return;
            }
            
            showLoading('批量抓取中', '开始批量抓取数据，请耐心等待...');
            addLog(`开始批量抓取: ${fetchType === 'custom' ? '自定义列表' : selectedGroup}`, 'info');
            
            let url = `/stockpereport/batch-fetch?fetchType=${fetchType}`;
            if (customStockList) url += `&customList=${encodeURIComponent(customStockList)}`;
            if (batchProcess20Quarters) url += '&process20Quarters=true';
            if (skipExisting) url += '&skipExisting=true';
            
            // 模拟进度更新（实际应用中可能需要WebSocket或轮询）
            let progress = 0;
            let progressInterval = setInterval(function() {
                progress += 5;
                if (progress <= 100) {
                    updateLoadingProgress(progress);
                }
            }, 2000);
            
            $.ajax({
                url: url,
                type: 'GET',
                success: function(data) {
                    clearInterval(progressInterval);
                    hideLoading();
                    
                    if (data.success) {
                        showToast('成功', data.message, 'success');
                        addLog(`批量抓取完成: 成功${data.successCount || 0}只，失败${data.failCount || 0}只`, 'success');
                        
                        // 刷新统计和列表
                        loadSystemStats();
                        loadRecentStocks();
                    } else {
                        showToast('失败', data.message, 'danger');
                        addLog(`批量抓取失败: ${data.message}`, 'error');
                    }
                },
                error: function() {
                    clearInterval(progressInterval);
                    hideLoading();
                    showToast('错误', '网络请求失败或服务器错误', 'danger');
                    addLog('批量抓取过程中发生网络错误', 'error');
                }
            });
        }
        
        // 取消批量抓取
        function cancelBatchFetch() {
            if (confirm('确定要取消批量抓取吗？')) {
                addLog('用户取消批量抓取操作', 'warning');
                // 这里可以实现取消正在进行的抓取任务
                showToast('提示', '已取消批量抓取操作', 'info');
            }
        }
        
        // 保存设置
        function saveSettings() {
            let settings = {
                fetchInterval: parseInt($('#fetchInterval').val()),
                timeout: parseInt($('#timeout').val()),
                retryCount: parseInt($('#retryCount').val()),
                useProxy: $('#useProxy').prop('checked'),
                enableDebug: $('#enableDebug').prop('checked')
            };
            
            // 保存到localStorage
            localStorage.setItem('stockpeFetchSettings', JSON.stringify(settings));
            
            showToast('成功', '设置已保存', 'success');
            addLog('用户设置已保存', 'info');
        }
        
        // 加载设置
        function loadSettings() {
            let savedSettings = localStorage.getItem('stockpeFetchSettings');
            if (savedSettings) {
                try {
                    let settings = JSON.parse(savedSettings);
                    $('#fetchInterval').val(settings.fetchInterval || 2000);
                    $('#timeout').val(settings.timeout || 30);
                    $('#retryCount').val(settings.retryCount || 3);
                    $('#useProxy').prop('checked', settings.useProxy || false);
                    $('#enableDebug').prop('checked', settings.enableDebug !== false);
                    addLog('已加载保存的用户设置', 'info');
                } catch (e) {
                    addLog('加载用户设置失败', 'error');
                }
            }
        }
        
        // 处理所有股票近20个季度数据
        function processAll20Quarters() {
            if (!confirm('确定要处理所有股票近20个季度的数据吗？这可能需要较长时间。')) {
                return;
            }
            
            showLoading('处理季度数据中', '正在处理所有股票的近20个季度数据，请耐心等待...');
            addLog('开始处理所有股票近20个季度数据', 'info');
            
            $.ajax({
                url: '/stockpereport/process-all-20quarters',
                type: 'GET',
                success: function(data) {
                    hideLoading();
                    if (data.success) {
                        showToast('成功', data.message, 'success');
                        addLog('季度数据处理完成', 'success');
                        loadSystemStats();
                    } else {
                        showToast('失败', data.message, 'danger');
                        addLog('季度数据处理失败: ' + data.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('错误', '网络请求失败，请稍后重试', 'danger');
                    addLog('季度数据处理过程中发生网络错误', 'error');
                }
            });
        }
        
        // 删除旧数据
        function deleteOldData() {
            let days = parseInt($('#oldDataDays').val()) || 365;
            
            if (!confirm(`确定要删除${days}天前的旧数据吗？此操作不可逆。`)) {
                return;
            }
            
            showLoading('删除旧数据中', `正在删除${days}天前的旧数据，请耐心等待...`);
            addLog(`开始删除${days}天前的旧数据`, 'warning');
            
            $.ajax({
                url: `/stockpereport/delete-old-data?days=${days}`,
                type: 'GET',
                success: function(data) {
                    hideLoading();
                    if (data.success) {
                        showToast('成功', data.message, 'success');
                        addLog(`旧数据删除完成，删除了${data.deletedCount || 0}条记录`, 'success');
                        loadSystemStats();
                    } else {
                        showToast('失败', data.message, 'danger');
                        addLog('旧数据删除失败: ' + data.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('错误', '网络请求失败，请稍后重试', 'danger');
                    addLog('旧数据删除过程中发生网络错误', 'error');
                }
            });
        }
        
        // 添加日志
        function addLog(message, type = 'info') {
            let logContainer = $('#logContainer');
            let timestamp = new Date().toLocaleString('zh-CN');
            let logItem = $(`<div class="log-item ${type}">[${timestamp}] ${message}</div>`);
            
            logContainer.append(logItem);
            logContainer.scrollTop(logContainer[0].scrollHeight);
            
            // 限制日志数量，防止页面过长
            if (logContainer.children().length > 100) {
                logContainer.children().first().remove();
            }
        }
        
        // 显示加载遮罩
        function showLoading(title = '处理中', message = '请稍候...') {
            $('#loadingTitle').text(title);
            $('#loadingMessage').text(message);
            $('#loadingProgress').css('width', '0%');
            $('#loadingPercentage').text('0%');
            $('#loadingOverlay').show();
        }
        
        // 隐藏加载遮罩
        function hideLoading() {
            $('#loadingOverlay').hide();
        }
        
        // 更新加载进度
        function updateLoadingProgress(progress) {
            $('#loadingProgress').css('width', progress + '%');
            $('#loadingPercentage').text(progress + '%');
        }
        
        // 显示提示消息
        function showToast(title, message, type) {
            $('#toastTitle').text(title);
            $('#toastMessage').text(message);
            
            let toast = $('#toast');
            toast.removeClass('bg-success bg-danger bg-info bg-warning');
            toast.addClass(`bg-${type}`);
            toast.addClass('text-white');
            
            toast.toast('show');
        }
        
        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '--';
            let date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }
    </script>
</body>
</html>